<?php
/**
 * 消息表的操作
 * @author Ju <hipop@126.com>
 *
 */
class Application_Model_DbTable_Msg extends Application_Model_DbTable_Base
{
    protected $_name = 'msg';
    
    /**
     * 根据类型获取一定量的消息
     * @param int $type
     * @param int $limit
     * @param int $userid 消息接收人
     * @return array
     */
    public function getListByType($type,$limit=20,$userid=-1)
    {
		$userM  = new Application_Model_DbTable_User();	    	
    	$userKV = $userM->getKVnameid();
    	
    	$select = $this->select();
		$select->where(" `type` = ? ",intval($type));		
		$select->where(" `to_user` = ? ",intval($userid));
		$select->limit(intval($limit),0);
		$select->order(" id DESC ");
		$redata= $this->fetchAll($select);
		$redata= $redata->toArray();
		
		foreach ($redata as &$d){
			$d["create_time"] 	= date("m-d H:i:s",$d["create_time"]);
			//$d["create_user"] 	= !empty($userKV[$d["create_user"]])?$userKV[$d["create_user"]]:"";			
			$d["from_user"] 	= !empty($userKV[$d["from_user"]])?$userKV[$d["from_user"]]:"";			
			$d["to_user"] 		= !empty($userKV[$d["to_user"]])?$userKV[$d["to_user"]]:"";			
		}
		return $redata;
    }
    
    /**
     * 获取某个客户相关的提醒
     * @param int $customer 用户id
     * @param int $limit 数量
     * @param array $timelimit 时间限制 时间戳数组[min,max]
     * @param int $userid 消息接受者
     */
    public function getAlarmByCustomer($customer,$limit=20,$timelimit=NULL,$userid=-1)
    {
    	$select = $this->select();
		$select->where(" `type` = ? ",Application_Model_Msg::TYPE_ALARM);		
		$select->where(" `to_user` = ? ",intval($userid));
		$select->where(" `foreign_value` = ? ",intval($customer));
		$select->where(" `foreign_key` = ? ",'customer');
		is_array($timelimit) && $select->where(" `alarm_time` BETWEEN {$timelimit[0]} AND {$timelimit[1]} ");
		$select->limit(intval($limit),0);
		$select->order(" id DESC ");
		$redata= $this->fetchAll($select);
		$redata= $redata->toArray();
		
		return $redata;
    }
    
}